<template>
	<view class="business-settled-wrapper">
		<uni-bankhome />
		<view>
			<h4>实名认证（请上传真实的信息，认证通过后将无法修改）</h4>
			<view class='form-wrapper'>
				<u-form :model="ruleForm" label-width="200rpx" ref="uForm">
					<u-form-item required label="执照号" prop="licenseNum">
						<div class="form-item" @click.stop="chooseImageYYZZ()">
							<u-input @click.stop="chooseImageYYZZ()" class="input" disabled
								v-model="ruleForm.licenseNum" placeholder="请识别您的营业执照号" />
							<u-icon @click.stop="chooseImageYYZZ()" name="camera-fill" size="32"></u-icon>
						</div>
					</u-form-item>
					<u-form-item required label="经营范围" prop="scope">
						<div class="form-item">
							<u-input class="input" v-model="ruleForm.scope" placeholder="请输入您的法定经营范围" />
						</div>
					</u-form-item>
					<u-form-item required label="店铺Logo" prop="storeLogo">
						<view class="image-flex-wrapper">
							<image v-if="ruleForm.storeLogo" @click="preview(ruleForm.storeLogo)" class="image"
								:src="ruleForm.storeLogo" mode=""></image>
							<button type="default" @click="chooseImage('storeLogo')" class="choose-image">+</button>
						</view>
					</u-form-item>
					<u-form-item required label="店铺/公司名称" prop="storeName">
						<div class="form-item">
							<u-input class="input" v-model="ruleForm.storeName" placeholder="请输入店铺名称" />
						</div>
					</u-form-item>
					<u-form-item required label="商家电话" prop="storePhone">
						<view class="form-item">
							<u-input class="input" v-model="ruleForm.storePhone" placeholder="请输入商家电话号码" />
						</view>
					</u-form-item>
					<u-form-item required label="店铺类型" prop="selfOperated">
						<div class="form-item">
							<u-radio-group :wrap="false" v-model="ruleForm.selfOperated">
								<u-radio name="0"> 商圈店铺 </u-radio>
								<u-radio name="1"> 电商店铺 </u-radio>
							</u-radio-group>
						</div>
					</u-form-item>
					<u-form-item required label="店内图片" prop="storeImage">
						<view class="image-flex-wrapper">
							<div class="image-wrapper" v-for="(item,index) in ruleForm.storeImage" :key="index">
								<image @click="preview(item,ruleForm.storeImage)" class="image" :src="item" mode="">
								</image>
								<u-icon name="trash-fill" color="#f51818" class="del" size="30"
									@click="ruleForm.storeImage.splice(index,1)"></u-icon>
							</div>
							<button v-if="ruleForm.storeImage.length<9" type="default"
								@click="chooseImage('storeImage')" class="choose-image">+</button>
						</view>
					</u-form-item>
					<u-form-item required label="开始时间" prop="sellTimeSta">
						<div class="form-item">
							<u-input class="input" v-model="ruleForm.sellTimeSta" disabled placeholder="请选择营业开始时间"
								@click="showday = true" />
							<u-icon name="arrow-right" color="#999999"></u-icon>
							<u-picker :params="params" v-model="showday" mode="time" :confirm-color="lightColor"
								@confirm="selltime">
							</u-picker>
						</div>
					</u-form-item>
					<u-form-item required label="结束时间" prop="sellTimeEnd">
						<div class="form-item">
							<u-input class="input" v-model="ruleForm.sellTimeEnd" disabled placeholder="请选择营业结束时间"
								@click="showdaysss = true" />
							<u-icon name="arrow-right" color="#999999"></u-icon>
							<u-picker :params="params" v-model="showdaysss" mode="time" :confirm-color="lightColor"
								@confirm="selectendTime"></u-picker>
						</div>
					</u-form-item>
					<u-form-item required label="所在区域" prop="storeAddressPath">
						<div class="form-item" @click.stop="openMap">
							<u-input @click.stop="openMap" class="input" disabled v-model="ruleForm.storeAddressPath"
								type="text" placeholder="选择位置-定位" />
							<u-icon @click.stop="openMap" name="map-fill" size="32" color="#999999"></u-icon>
						</div>
					</u-form-item>
					<u-form-item required label="详细地址" prop="storeAddressDetail">
						<div class="form-item">
							<u-input class="input" v-model="ruleForm.storeAddressDetail" placeholder="请输入店铺地址" />
						</div>
					</u-form-item>
					<u-form-item required label="店铺简介" prop="storeDesc">
						<div class="form-item">
							<u-input class="input" v-model="ruleForm.storeDesc" placeholder="请输入店铺简介" />
						</div>
					</u-form-item>
					<u-form-item required label="店铺合同" prop="isHaveContract">
						<div class="form-item">
							<u-radio-group :wrap="false" v-model="ruleForm.isHaveContract">
								<u-radio name="0"> 无 </u-radio>
								<u-radio name="1"> 有 </u-radio>
							</u-radio-group>
						</div>
					</u-form-item>
					<u-form-item v-if="ruleForm.isHaveContract=='1'" required label="店铺提现折扣(%)" prop="discount">
						<div class="form-item">
							<u-input class="input" v-model="ruleForm.discount" type="number" placeholder="请输入店铺提现折扣" />
						</div>
					</u-form-item>

					<u-form-item required label="执照照片" prop="licencePhoto">
						<view class="image-flex-wrapper">
							<image v-if="ruleForm.licencePhoto" class="image" :src="ruleForm.licencePhoto" mode="">
							</image>
							<button type="default" @click="chooseImage('licencePhoto')" class="choose-image">+</button>
						</view>
					</u-form-item>
					<u-form-item required label="资质许可照片" prop="qualificationLicensePhoto">
						<view class="image-flex-wrapper">
							<div class="image-wrapper" v-for="(item,index) in ruleForm.qualificationLicensePhoto"
								:key="index">
								<image @click="preview(item,ruleForm.qualificationLicensePhoto)" class="image"
									:src="item" mode=""></image>
								<u-icon name="trash-fill" color="#f51818" class="del" size="30"
									@click="ruleForm.qualificationLicensePhoto.splice(index,1)"></u-icon>
							</div>
							<button v-if="ruleForm.qualificationLicensePhoto.length<5" type="default"
								@click="chooseImage('qualificationLicensePhoto')" class="choose-image">+</button>
						</view>
					</u-form-item>
					<u-form-item required label="经营者身份证正面" prop="legalPhotoF" labelWidth="240rpx">
						<view class="image-flex-wrapper">
							<image v-if="ruleForm.legalPhotoF" @click="preview(ruleForm.legalPhotoF)" class="image"
								:src="ruleForm.legalPhotoF" mode=""></image>
							<button type="default" @click="chooseImage('legalPhotoF')" class="choose-image">+</button>
						</view>
					</u-form-item>
					<u-form-item required label="经营者身份证反面" prop="legalPhotoback" labelWidth="240rpx">
						<view class="image-flex-wrapper">
							<image v-if="ruleForm.legalPhotoback" @click="preview(ruleForm.legalPhotoback)"
								class="image" :src="ruleForm.legalPhotoback" mode=""></image>
							<button type="default" @click="chooseImage('legalPhotoback')"
								class="choose-image">+</button>
						</view>
					</u-form-item>
				</u-form>
				<u-button :customStyle="{'background':$lightColor,'color':'#fff' }" @click="submit">提交</u-button>
			</view>
		</view>
		<view class="tips">
			<view>您提交的信息正在审核</view>
			<view>提交认证申请后，工作人员将在三个工作日进行核对完成审核</view>
		</view>
		<uniMap v-if="mapFlage" @close="closeMap" @callback="callBackAddress" />
	</view>
</template>
<script>
	import {
		applyDistribution,
		ApplyBuyer
	} from "@/api/goods";
	import {
		checkBankno
	} from "@/utils/Foundation";
	import {
		getBusinessLicense,
		getBusinessSettleInfo
	} from "@/api/store.js"
	import storage from "@/utils/storage.js";
	import api from "@/config/api.js";
	import uFormItem from "@/uview-ui/components/u-form-item/u-form-item.vue";
	import uniMap from "@/components/map/map.vue";
	export default {
		data() {
			return {
				mapFlage: false, // 地图是否打开
				params: {
					year: false,
					month: false,
					day: false,
					hour: true,
					minute: true,
					second: false
				},
				showday: false, // 开始时间
				showdaysss: false, //结束时间
				ruleForm: {
					// 营业执照号
					licenseNum: '',
					// 法定经营范围
					scope: '',
					// 店铺Logo
					storeLogo: '',
					// 店铺名称
					storeName: '',
					selfOperated: '0', // 店铺类型
					// 商家电话
					storePhone: '',
					// 店铺图片
					storeImage: [],
					// 地址
					storeAddressIdPath: '',
					storeAddressPath: '',
					// adcode
					adCode: '',
					// 纬度
					lat: '',
					// 经度
					lon: '',
					// 详细地址
					storeAddressDetail: '',
					// 店铺简介
					storeDesc: '',
					isHaveContract: '0', // 店铺合同
					discount: '', // 店铺提现折扣
					licencePhoto: '', // 营业执照照片
					qualificationLicensePhoto: [], // 资质许可证照片
					// 法人身份证照片
					legalPhotoF: '',
					legalPhotoback: '',
					sellTimeSta: '',
					sellTimeEnd: ''
				},
				rules: {
					licenseNum: [{
						required: true,
						message: "请输入营业执照号",
						trigger: ["change", "blur"],
					}, {
						validator: (rule, value, callback) => {
							if (value.length != 15 && value.length != 18) {
								return false
							} else {
								return true
							}
						},
						message: "请输入15位或18位的执照号",
						trigger: ["change", "blur"],
					}],
					scope: [{
						required: true,
						message: "请输入经营范围",
						trigger: ["change", "blur"],
					}],
					storeLogo: [{
						required: true,
						message: "请上传店铺Logo",
						trigger: "change"
					}],
					storeName: [{
						required: true,
						message: "请输入店铺名称",
						trigger: ["change", "blur"],
					}],
					storePhone: [{
							required: true,
							message: "电话不能为空",
							trigger: ["blur", "change"],
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: "电话号码格式不正确",
							trigger: ["change", "blur"],
						},
					],
					storeImage: [{
						validator: (rule, value, callback) => {
							if (value.length === 0) {
								return false
							} else {
								return true
							}
						},
						message: "请选择店铺图片",
						trigger: "change"
					}],
					sellTimeSta: [{
						required: true,
						message: "请选择开始时间",
						trigger: ["change", "blur"],
					}],
					sellTimeEnd: [{
						required: true,
						message: "请选择结束时间",
						trigger: ["change", "blur"],
					}],
					storeAddressPath: [{
						required: true,
						message: "请选择店铺位置",
						trigger: ["change", "blur"],
					}],
					storeAddressDetail: [{
						required: true,
						message: "请输入店铺地址",
						trigger: ["change", "blur"],
					}],
					storeDesc: [{
						required: true,
						min: 6,
						max: 200,
						message: '请输入6-200个字之间店铺简介'
					}, ],
					discount: [{
						required: true,
						message: "请输入店铺折扣",
						trigger: ["change", "blur"],
					}, {
						validator: (rule, value, callback) => {
							if (this.ruleForm.isHaveContract === '1') {
								return /^([1-9][0-9]{0,1}|100)$/.test(value)
							} else {
								return true
							}
						},
						message: "请输入1-100的整数",
						trigger: ["change", "blur"],
					}],
					licencePhoto: [{
						required: true,
						message: "请选择执照照片",
						trigger: "change"
					}],
					qualificationLicensePhoto: [{
						validator: (rule, value, callback) => {
							console.log(value)
							if (value.length === 0) {
								return false
							} else {
								return true
							}
						},
						message: "请选择资质许可证照片",
						trigger: "change"
					}],
					legalPhotoF: [{
						validator: (rule, value, callback) => {
							console.log(value)
							if (value.length === 0) {
								return false
							} else {
								return true
							}
						},
						message: "请选择法人身份证照片",
						trigger: "change"
					}],
					legalPhotoback: [{
						required: true,
						message: "请选择法人身份证照片",
						trigger: "change"
					}],

				}
			};
		},
		components: {
			uFormItem,
			uniMap
		},
		onLoad(options) {
			this.$options.filters.forceLogin()
			// edit 编辑  获取店铺详情，并回显数据 --start--
			if (options.type === 'edit') {
				getBusinessSettleInfo().then((res) => {
					console.log(res.data.result)
					let data = res.data.result
					this.ruleForm = {
						// 营业执照号
						licenseNum: data.licenseNum,
						// 法定经营范围
						scope: data.scope,
						// 店铺Logo
						storeLogo: data.storeLogo,
						// 店铺名称
						storeName: data.storeName,
						selfOperated: data.selfOperated,
						// 商家电话
						storePhone: data.storePhone,
						// 商家图片
						storeImage: data.storeImage ? data.storeImage.split(',') : [],
						// 地址
						storeAddressIdPath: data.storeAddressIdPath,
						storeAddressPath: data.storeAddressPath,
						// adcode
						adCode: data.adCode,
						// 纬度
						lat: data.lat,
						// 经度
						lon: data.lon,
						// 详细地址
						storeAddressDetail: data.storeAddressDetail,
						// 店铺简介
						storeDesc: data.storeDesc,
						isHaveContract: data.isHaveContract,
						// 店铺提现折扣
						discount: data.discount,
						licencePhoto: data.licencePhoto, // 营业执照照片
						qualificationLicensePhoto: data.qualificationLicensePhoto.split(','), // 资质许可证照片
						// 法人身份证照片
						legalPhotoF: data.legalPhoto ? data.legalPhoto.split(',')[0] : '',
						legalPhotoback: data.legalPhoto ? data.legalPhoto.split(',')[1] : '',
						sellTimeSta: data.sellTimeSta,
						sellTimeEnd: data.sellTimeEnd,
					}
				})
			}
			// edit 编辑  获取店铺详情，并回显数据 --end--
		},
		methods: {
			// 店铺所在区域 选择定位 --start--
			// 打开地图
			openMap() {
				this.mapFlage = true;
			},
			// 关闭地图
			closeMap() {
				this.mapFlage = false;
			},
			// 打开地图并访问权限
			clickUniMap() {
				let that = this
				// #ifdef APP-PLUS
				if (plus.os.name == "iOS") {
					// ios系统
					permision.judgeIosPermission("location") ?
						(this.mapFlage = true) :
						this.refuseMapOuther();
				} else {
					// 安卓
					this.requestAndroidPermission(
						"android.permission.ACCESS_FINE_LOCATION"
					);
				}
				// #endif

				// #ifndef APP-PLUS
				this.mapFlage = true;
				// #endif
			},
			// 选择地址后数据的回调
			callBackAddress(val) {
				let that = this
				let addressData = {}
				uni.showLoading({
					title: "加载中",
				});
				if (val.regeocodeData && val) {
					let address = val.regeocodeData;
					addressData.storeAddressIdPath = val.data.result.id; // 地址id分割
					addressData.storeAddressPath = val.data.result.name; //地址名称， '，'分割
					addressData.adCode = val.regeocodeData.addressComponent.adCode
					addressData.lat = val.latitude; //纬度
					addressData.lon = val.longitude; //经度
					if (addressData.storeAddressPath) {
						let patharr=addressData.storeAddressPath.split(',')
						if(patharr.length==4){
							patharr.pop()
						}
						addressData.storeAddressPath = patharr.join(' ')
					}
					if (addressData.storeAddressIdPath) {
						let patharr=addressData.storeAddressIdPath.split(',')
						if(patharr.length==4){
							patharr.pop()
						}
						addressData.storeAddressIdPath = patharr.join(' ')
					}
					this.ruleForm.storeAddressIdPath = addressData.storeAddressIdPath
					this.ruleForm.storeAddressPath = addressData.storeAddressPath
					this.ruleForm.adCode = addressData.adCode
					this.ruleForm.lat = addressData.lat; //纬度
					this.ruleForm.lon = addressData.lon; //经度
					uni.hideLoading();
					setTimeout(() => {
						that.$refs.uForm.validate((valid) => {
							return true
						})
					}, 20)
				}
				this.closeMap() //关闭地图
			},
			// 店铺所在区域 选择定位 --end--
			/**
			 * 选择时间
			 */
			selltime(time) {
				let that = this
				this.ruleForm.sellTimeSta = `${time.hour}:${time.minute}`;
				setTimeout(() => {
					that.$refs.uForm.validate((valid) => {
						return true
					})
				}, 20)
			},
			selectendTime(time) {
				let that = this
				if (!this.ruleForm.sellTimeSta) {
					uni.showToast({
						title: "请选择营业开始时间",
						duration: 2000,
						icon: "none",
					});
					return;
				}
				this.ruleForm.sellTimeEnd = `${time.hour}:${time.minute}`;
				setTimeout(() => {
					that.$refs.uForm.validate((valid) => {
						return true
					})
				}, 20)
			},
			// 上传照片
			chooseImage(type, fileName) {
				let Token = storage.getAccessToken()
				let that = this
				let count = 1
				if (type == 'qualificationLicensePhoto') {
					count = 5 - this.ruleForm.qualificationLicensePhoto.length
				}
				if (type == 'storeImage') {
					count = 9 - this.ruleForm.storeImage.length
				}
				uni.chooseImage({
					count: count,
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: function(res) {
						var tempFilePaths = res.tempFilePaths
						for (let i = 0; i < tempFilePaths.length; i++) {
							uni.uploadFile({
								url: api.common + '/upload/file',
								fileType: "image",
								filePath: tempFilePaths[i],
								name: 'file',
								ruleForm: {},
								'content-type': 'multipart/form-data',
								header: {
									accessToken: Token,
									'content-type': 'multipart/form-data'
								}, // 设置请求的 header
								success: function(res) {
									res = JSON.parse(res.data)
									if (type == 'qualificationLicensePhoto' || type ==
										'storeImage') {
										that.ruleForm[type].push(res.result)
									} else {
										that.ruleForm[type] = res.result
									}
									setTimeout(() => {
										that.$refs.uForm.validate((valid) => {
											return true
										})
									}, 20)
								},
								fail(res) {
									console.log(res)
								},
								complete(res) {
									console.log(res)
								},
							})
						}

					}
				})
			},
			//营业执照 上传以及信息识别
			chooseImageYYZZ() {
				let Token = storage.getAccessToken()
				let that = this
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: function(res) {
						var tempFilePaths = res.tempFilePaths
						for (let i = 0; i < tempFilePaths.length; i++) {
							uni.uploadFile({
								url: api.common + '/upload/file',
								fileType: "image",
								filePath: tempFilePaths[i],
								name: 'file',
								ruleForm: {},
								'content-type': 'multipart/form-data',
								header: {
									accessToken: Token,
									'content-type': 'multipart/form-data' // 设置请求的 header
								},
								success: function(res) {
									res = JSON.parse(res.data)
									if (res.code == 200) {
										let imgUrl = res.result
										that.distinguish(imgUrl)
									} else {
										this.toast(res.message)
									}
								}
							})
						}
					}
				})
			},
			// 证件识别
			distinguish(url) {
				uni.showLoading({
					title: "识别中",
				});
				// 开始识别
				getBusinessLicense({
					url,
				}).then((res) => {
					if (res.data.code === 200) {
						const data = res.data.result;
						console.log(data);
						let licenseNum = data.licenseNum
						this.ruleForm.licenseNum = licenseNum
						uni.hideLoading();
					} else {
						uni.showToast({
							title: res.data.message,
							icon: "none"
						})
					}
				}).catch(err => {
					uni.showToast({
						title: err,
						icon: "none"
					})
				})
			},
			submit() {
				this.$refs.uForm.validate((valid) => {
					if (valid) {
						ApplyBuyer({
							...this.ruleForm,
							qualificationLicensePhoto: this.ruleForm.qualificationLicensePhoto.join(','),
							legalPhoto: this.ruleForm.legalPhotoF + ',' + this.ruleForm.legalPhotoback,
							storeImage: this.ruleForm.storeImage.join(',')
						}).then((res) => {
							if (res.data.success) {
								uni.showToast({
									title: "认证提交成功!",
									duration: 2000,
									icon: "none",
								});
								setTimeout(() => {
									uni.navigateBack();
								}, 500);
							} else {
								uni.showToast({
									title: res.data.message,
									duration: 2000,
									icon: "none",
								});
							}
						});
					} else {
						uni.showToast({
							title: "请填写有效信息",
							duration: 2000,
							icon: "none",
						});
					}
				});
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
	};
</script>
<style lang="scss" scoped>
	.business-settled-wrapper {
		padding: 32rpx;

		.form-wrapper {
			padding: 0 32upx;
		}

		.form-item {
			background-color: #ffffff;
			padding: 0 24upx;
			border-radius: 8upx;
			display: flex;

			.input {
				flex: 1;
			}
		}

		.tips {
			margin-top: 20rpx;
			font-size: 24rpx;
			color: #999;
		}

		.image-flex-wrapper {
			display: flex;
			flex: 0 0 140upx;
			flex-direction: row;
			flex-wrap: wrap;

			.image-wrapper {
				position: relative;

				.del {
					position: absolute;
					top: 24upx;
					right: 24upx;
				}
			}

			.image {
				margin: 12upx;
				width: 140upx;
				height: 140upx;
				vertical-align: middle;
			}

			.choose-image {
				margin: 12upx;
				width: 140upx;
				height: 140upx;
				line-height: 120upx;
				font-size: 40px;
				border: 1px dashed #999;
			}
		}
	}
</style>
